package com.jahe.learn.netty4.websocket;

import com.jahe.learn.netty4.ThreadPool;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;

import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;

/**
 * 支持连接心跳检测 的 websocket 服务器
 * @author: jahe.lai
 * @create: 2019-12-25 17:09
 */
public class WebSocketServer {

    public static void main(String[] args) {
        // 默认线程数是 CPU 核心数 * 2
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            // 启动 和 配置属性相关的 辅助类
            ServerBootstrap bootstrap = new ServerBootstrap();
            // 配置相关属性
            bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {

                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            pipeline.addLast(new IdleStateHandler(32, 0, 50, TimeUnit.SECONDS))
                                    .addLast(new HeartBeatHandler())
                                    .addLast(new HttpServerCodec())
                                    .addLast(new ChunkedWriteHandler())
                                    .addLast(new HttpObjectAggregator(8192))
                                    .addLast(new WebSocketServerProtocolHandler("/ws"))
                                    .addLast(new WebSocketFrameHandler());
                        }
                    });
            ChannelFuture channelFuture = bootstrap.bind(new InetSocketAddress(8899)).sync();
            System.out.println(Thread.currentThread().getName() + " server start success.");

            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ThreadPool.shutdown();
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

    }
}
